import React, { useEffect, useState } from 'react';
import { Row, Tabs, Table, Input, Col, Button, message, Form } from 'antd';
import services from '../../../../services/api';

const { TabPane } = Tabs;
const { TextArea } = Input;

const Test = (props) => {
  const { closeModal, value } = props;
  const [data, setData] = useState([]);
  const [requestJSON, setRequestJSON] = useState('{}');
  const [responseJSON, setResponseJSON] = useState('');

  useEffect(() => {
    if (Object.values(value).length) {
      getInputFieldList();
    }
  }, []);

  const getInputFieldList = async () => {
    const { third_list_config_id } = value;
    const { code, data, msg } = await services.outerList.getNameListDetail({ third_list_config_id });
    if (!code) {
      setData(data.input_field_list);
    } else {
      message.error(msg);
    }
  };

  const getColumns = () => [
    {
      title: '字段名',
      dataIndex: 'param_name',
    },
    {
      title: '类型',
      dataIndex: 'data_type',
    },
    {
      title: '长度',
      dataIndex: 'max_length',
    },
    {
      title: '必填',
      dataIndex: 'required',
      render: (_, record) => {
        return record.required === 1 ? '是' : '否';
      },
    },
    {
      title: '输入值',
      dataIndex: 'value',
      render: (text, { param_code, param_id }) => {
        return <Input value={text} onChange={(e) => handleChange(e.target.value, param_code, param_id)} />;
      },
    },
  ];

  const isJson = (value) => {
    try {
      return typeof JSON.parse(value) === 'object';
    } catch (error) {
      return false;
    }
  };

  const handleChange = (value, code, id) => {
    const tempData = [...data];
    const isTempJson = isJson(requestJSON);
    if (requestJSON && !isTempJson) return;
    const tempJson = requestJSON ? isTempJson && JSON.parse(requestJSON) : {};
    tempJson[code] = value;
    setRequestJSON(JSON.stringify(tempJson));
    const index = tempData.findIndex((item) => item.param_id === id);
    tempData[index].value = value;
    setData(tempData);
  };

  const handleRequestChange = (value) => {
    setRequestJSON(value);
    if (isJson(value)) {
      const tempData = [...data];
      const tempValue = JSON.parse(value);
      tempData.forEach((item) => {
        if (tempValue[item.param_code]) {
          item.value = tempValue[item.param_code];
        } else {
          item.value = '';
        }
      });
      setData(tempData);
    }
  };

  const handleTest = async () => {
    const { url, script: groovyScript, data_type, error_value, return_value } = value;
    if (data.some((item) => item.required && !item.value)) {
      return message.warning('请填写必填项');
    }
    if (!isJson(requestJSON)) return;
    const params = {
      url,
      groovyScript,
      reqJson: requestJSON,
      data_type,
      error_value,
      return_value,
    };
    const res = await services.customParams.test(params);
    setResponseJSON(JSON.stringify(res));
  };

  const validateObj = {
    status: !isJson(requestJSON) ? 'error' : '',
    help: !isJson(requestJSON) ? 'json格式不正确' : '',
  };

  return (
    <div>
      <Row gutter={20}>
        <Col span={14}>
          <Tabs defaultActiveKey='1'>
            <TabPane tab='输入参数' key='1'>
              <Table columns={getColumns()} dataSource={data} rowKey='param_id' />
            </TabPane>
          </Tabs>
        </Col>
        <Col span={10}>
          <p>请求内容</p>
          <Form.Item validateStatus={validateObj.status} help={validateObj.help}>
            <TextArea rows={14} value={requestJSON} onChange={(e) => handleRequestChange(e.target.value)} />
          </Form.Item>
          <p>返回内容</p>
          <TextArea rows={10} disabled value={responseJSON} style={{ color: '#888' }} />
        </Col>
      </Row>
      <div className='form-btn'>
        <Button type='primary' onClick={handleTest}>
          测试
        </Button>
        <Button className='marl10' onClick={() => closeModal()}>
          取消
        </Button>
      </div>
    </div>
  );
};
export default Test;
